import base64
import json
from .baidu_ocr import BaiduOCR

# TODO: 请确保在 baidu_ocr_cnf.py 中配置了正确的 API Key 和 Secret Key
# TODO: 请替换为自己的图片路径
IMAGE_PATH = r"D:\temp\pic\test\ocr_02.jpg"


def test_baidu_ocr_from_path(ocr_client: BaiduOCR, image_path: str):
    """测试从文件路径进行OCR识别"""
    print("--- 正在测试从文件路径识别 ---")
    try:
        result = ocr_client.recognize_text(image_path, is_path=True)
        print("识别结果:")
        print(json.dumps(result, indent=4, ensure_ascii=False))
    except Exception as e:
        print(f"发生错误: {e}")


def test_baidu_ocr_from_base64(ocr_client: BaiduOCR, image_path: str):
    """测试从Base64字符串进行OCR识别"""
    print("\n--- 正在测试从Base64字符串识别 ---")
    try:
        with open(image_path, "rb") as f:
            image_base64 = base64.b64encode(f.read()).decode("utf-8")

        result = ocr_client.recognize_text(image_base64, is_path=False)
        print("识别结果:")
        print(json.dumps(result, indent=4, ensure_ascii=False))
    except FileNotFoundError:
        print(f"错误: 测试图片未找到，请检查路径 {image_path}")
    except Exception as e:
        print(f"发生错误: {e}")


def test_baidu_ocr_from_url(ocr_client: BaiduOCR, image_url: str):
    """测试从URL进行OCR识别"""
    print("\n--- 正在测试从URL识别 ---")
    try:
        result = ocr_client.recognize_text_from_url(image_url)
        print("识别结果:")
        print(json.dumps(result, indent=4, ensure_ascii=False))
    except Exception as e:
        print(f"发生错误: {e}")


if __name__ == "__main__":
    try:
        # 1. 初始化BaiduOCR客户端
        baidu_ocr_client = BaiduOCR()
        print("BaiduOCR 客户端初始化成功。")

        # 2. 从文件路径测试
        test_baidu_ocr_from_path(baidu_ocr_client, IMAGE_PATH)

        # 3. 从Base64字符串测试
        test_baidu_ocr_from_base64(baidu_ocr_client, IMAGE_PATH)

        # 4. 从URL测试
        TEST_IMAGE_URL = "https://video.people.cn/userUpload/1739759454736028/1743494136274391/picture/screenshot-18-57-55.png"
        test_baidu_ocr_from_url(baidu_ocr_client, TEST_IMAGE_URL)

    except (ValueError, ConnectionError) as e:
        print(f"客户端初始化或连接失败: {e}")
    except FileNotFoundError:
        print(f"错误: 测试图片未找到，请检查路径 {IMAGE_PATH}")
